package com.yoyo.ad.toutiao;

import android.content.Context;
import android.os.Build;
import android.util.DisplayMetrics;
import android.util.SparseArray;
import android.util.SparseBooleanArray;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;

import com.bytedance.sdk.openadsdk.AdSlot;
import com.bytedance.sdk.openadsdk.TTAdNative;
import com.bytedance.sdk.openadsdk.TTBannerAd;
import com.bytedance.sdk.openadsdk.TTFeedAd;
import com.bytedance.sdk.openadsdk.TTNativeExpressAd;
import com.yoyo.ad.confusion.AdManage;
import com.yoyo.ad.main.IAdBannerListener;
import com.yoyo.ad.main.IAdClick;
import com.yoyo.ad.main.IAdFactory_;
import com.yoyo.ad.main.IAdInteractionListener;
import com.yoyo.ad.main.IAdView;
import com.yoyo.ad.main.YoYoAd;
import com.yoyo.ad.utils.AnalysisUtils;
import com.yoyo.ad.utils.DensityUtil;

import java.util.ArrayList;
import java.util.List;

public class TouTiaoAdFactory implements IAdFactory_ {

    private IAdView mAdView;
    private IAdBannerListener mAdBannerListener;
    private IAdInteractionListener mAdInteractionListener;
    private Context mContext;
    private TTAdNative mTTAdNative;
    private final int adType = AdManage.TOU_TIAO;
    private int mWidth;

    private SparseArray<Long> adIds = new SparseArray<>();
    private SparseBooleanArray isIpReports = new SparseBooleanArray();

    public TouTiaoAdFactory(Context context, TTAdNative ttAdBean) {
        mContext = context;
        mTTAdNative = ttAdBean;
        DisplayMetrics outMetrics = new DisplayMetrics();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
            ((WindowManager) context.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay().getRealMetrics(outMetrics);
        } else {
            ((WindowManager) context.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay().getMetrics(outMetrics);
        }
        mWidth = outMetrics.widthPixels;
    }

    @Override
    public void setAdView(IAdView adView) {
        if (mAdView == null && adView != null)
            mAdView = adView;
    }

    @Override
    public void setAdBannerListener(IAdBannerListener adView) {
        if (mAdBannerListener == null && adView != null)
            mAdBannerListener = adView;
    }

    @Override
    public void setAdInteractionListener(IAdInteractionListener adInteractionListener) {
        if (mAdInteractionListener == null && adInteractionListener != null)
            mAdInteractionListener = adInteractionListener;
    }


    @Override
    public void setConfig(long adId, int adPositionId, boolean isIpReport) {
        adIds.put(adPositionId, adId);
        isIpReports.put(adPositionId, isIpReport);
    }

    @Override
    public void getYoyoAd(final int position, final int requestCode, int size, String adPlaceId, int type) {
        //feed广告请求类型参数
        AdSlot adSlot = new AdSlot.Builder()
                .setCodeId(adPlaceId)
                .setSupportDeepLink(true)
                .setImageAcceptedSize(640, 320)
                .setAdCount(size)
                .build();
        //调用feed广告异步请求接口
        mTTAdNative.loadFeedAd(adSlot, new TTAdNative.FeedAdListener() {
            @Override
            public void onError(int code, String message) {
                AnalysisUtils.addStatistics(adIds.get(position, 0L), AnalysisUtils.TYPE_FAIL);
                mAdView.adFail(requestCode, message);
                AdManage.showAdSuccess(mContext, AdManage.TENCENT, adIds.get(position, 0L),
                        position, isIpReports.get(position, false));
            }

            @Override
            public void onFeedAdLoad(List<TTFeedAd> arg0) {
                AdManage.showAdSuccess(mContext, AdManage.TENCENT, adIds.get(position, 0L),
                        position, isIpReports.get(position, false));
                int size1 = arg0.size();
                List<YoYoAd> list = new ArrayList<>(size1);
                for (TTFeedAd n : arg0) {
                    list.add(new ToutiaoYoYoAd(n, new IAdClick() {
                        @Override
                        public void onAdClick(View view) {
                            AnalysisUtils.addStatistics(adIds.get(position, 0L), AnalysisUtils.TYPE_CLICK);
                            if (mAdView != null)
                                mAdView.onAdClick(requestCode, view);
                        }

                        @Override
                        public void onAdShow() {
                            AnalysisUtils.addStatistics(adIds.get(position, 0L), AnalysisUtils.TYPE_PRESENT);
                        }
                    }));
                }
                if (mAdView != null)
                    mAdView.adSuccess(requestCode, list);
            }
        });
    }

    @Override
    public void getExpressAd(final int position, final int requestCode, String adPlaceId, int size, int width) {
        //step4:创建广告请求参数AdSlot,具体参数含义参考文档
        AdSlot adSlot = new AdSlot.Builder()
                .setCodeId(adPlaceId) //广告位id
                .setSupportDeepLink(true)
                .setAdCount(1) //请求广告数量为1到3条
                .setExpressViewAcceptedSize(DensityUtil.px2dp(mContext, width), 0) //期望模板广告view的size,单位dp
                .setImageAcceptedSize(640, 320)//这个参数设置即可，不影响模板广告的size
                .build();
        //step5:请求广告，对请求回调的广告作渲染处理
        mTTAdNative.loadNativeExpressAd(adSlot, new TTAdNative.NativeExpressAdListener() {
            @Override
            public void onError(int code, String message) {
                AnalysisUtils.addStatistics(adIds.get(position, 0L), AnalysisUtils.TYPE_FAIL);
                mAdView.adFail(requestCode, message);
                AdManage.showAdSuccess(mContext, AdManage.TENCENT, adIds.get(position, 0L),
                        position, isIpReports.get(position, false));
            }

            @Override
            public void onNativeExpressAdLoad(List<TTNativeExpressAd> arg0) {
                AdManage.showAdSuccess(mContext, AdManage.TENCENT, adIds.get(position, 0L),
                        position, isIpReports.get(position, false));
                int size1 = arg0.size();
                List<YoYoAd> list = new ArrayList<>(size1);
                for (TTNativeExpressAd n : arg0) {
                    n.setExpressInteractionListener(new TTNativeExpressAd.ExpressAdInteractionListener() {
                        @Override
                        public void onAdClicked(View view, int i) {
                            AnalysisUtils.addStatistics(adIds.get(position, 0L), AnalysisUtils.TYPE_CLICK);
                            if (mAdView != null)
                                mAdView.onAdClick(requestCode, view);
                        }

                        @Override
                        public void onAdShow(View view, int i) {
                            AnalysisUtils.addStatistics(adIds.get(position, 0L), AnalysisUtils.TYPE_PRESENT);
                        }

                        @Override
                        public void onRenderFail(View view, String s, int i) {
                            AnalysisUtils.addStatistics(adIds.get(position, 0L), AnalysisUtils.TYPE_FAIL);
                        }

                        @Override
                        public void onRenderSuccess(View view, float v, float v1) {
                        }
                    });
//                    n.render();
                    list.add(new ToutiaoYoYoAd(n));
                }
                if (mAdView != null)
                    mAdView.adSuccess(requestCode, list);
            }
        });
    }

    @Override
    public void getBanner(int position, final int requestCode, String adPlaceId, final ViewGroup adsParent, int width, int height) {
        adsParent.setVisibility(View.GONE);
        adsParent.removeAllViews();
        //step4:创建广告请求参数AdSlot,具体参数含义参考文档
        AdSlot adSlot = new AdSlot.Builder()
                .setCodeId(adPlaceId) //广告位id   909940853 "913596261"
                .setSupportDeepLink(true)
                .setImageAcceptedSize(width, height)//600, 90
                .build();
//        mTTAdNative.loadNativeAd(adSlot, new TTAdNative.NativeAdListener() {
//            @Override
//            public void onError(int i, String s) {
//                if (mAdBannerListener != null)
//                    mAdBannerListener.adFail(requestCode, s);
//
//            }
//
//            @Override
//            public void onNativeAdLoad(List<TTNativeAd> list) {
//                if(list.size()>0){
//                    ToutiaoYoYoAd toutiaoYoYoAd = new ToutiaoYoYoAd(list.get(0));
//                    Log.e(YoYoConfig.TAG, toutiaoYoYoAd.toString());
//                }
//            }
//        });

        //step5:请求广告，对请求回调的广告作渲染处理
        mTTAdNative.loadBannerAd(adSlot, new TTAdNative.BannerAdListener() {

            @Override
            public void onError(int code, String message) {
                if (mAdBannerListener != null)
                    mAdBannerListener.adFail(requestCode, message);
            }

            @Override
            public void onBannerAdLoad(final TTBannerAd ad) {
                if (ad == null) {
                    if (mAdBannerListener != null)
                        mAdBannerListener.adFail(requestCode, "no ad");
                    return;
                }
                View bannerView = ad.getBannerView();
                if (bannerView == null) {
                    if (mAdBannerListener != null)
                        mAdBannerListener.adFail(requestCode, "no ad");
                    return;
                }
                ad.setBannerInteractionListener(new TTBannerAd.AdInteractionListener() {
                    @Override
                    public void onAdClicked(View view, int i) {
                        if (mAdBannerListener != null)
                            mAdBannerListener.adClick(requestCode);
                    }

                    @Override
                    public void onAdShow(View view, int i) {
                        if (mAdBannerListener != null)
                            mAdBannerListener.adShow(requestCode);
                    }
                });
                //设置轮播的时间间隔  间隔在30s到120秒之间的值，不设置默认不轮播
                ad.setSlideIntervalTime(30 * 1000);
                adsParent.removeAllViews();
                adsParent.addView(bannerView);
                adsParent.setVisibility(View.VISIBLE);
            }
        });
        AdManage.showAdSuccess(mContext, adType, adIds.get(position, 0L),
                position, isIpReports.get(position, false));
    }

    @Override
    public void getInteraction(final int position, final int requestCode, String adPlaceId) {
        AdSlot adSlot = new AdSlot.Builder()
                .setCodeId(adPlaceId) //广告位id
                .setSupportDeepLink(true)
                .setAdCount(1) //请求广告数量为1到3条
                .setExpressViewAcceptedSize(DensityUtil.px2dp(mContext, (int) (mWidth * 0.8)), 0) //期望模板广告view的size,单位dp
                .setImageAcceptedSize(640, 320)//这个参数设置即可，不影响模板广告的size
                .build();
        //step5:请求广告，调用插屏广告异步请求接口
        mTTAdNative.loadInteractionExpressAd(adSlot, new TTAdNative.NativeExpressAdListener() {
            @Override
            public void onError(int i, String s) {
                AnalysisUtils.addStatistics(adIds.get(position, 0L), AnalysisUtils.TYPE_FAIL);
                if (mAdInteractionListener != null)
                    mAdInteractionListener.adFail(requestCode, s);
                AdManage.showAdSuccess(mContext, AdManage.TENCENT, adIds.get(position, 0L),
                        position, isIpReports.get(position, false));
            }

            @Override
            public void onNativeExpressAdLoad(List<TTNativeExpressAd> arg0) {
                AdManage.showAdSuccess(mContext, AdManage.TENCENT, adIds.get(position, 0L),
                        position, isIpReports.get(position, false));
                if (arg0 != null) {
                    if (arg0.size() > 0) {
                        final TTNativeExpressAd n = arg0.get(0);
                        n.setExpressInteractionListener(new TTNativeExpressAd.AdInteractionListener() {
                            @Override
                            public void onAdDismiss() {
                                if (mAdInteractionListener != null)
                                    mAdInteractionListener.adDismissed(requestCode);
                            }

                            @Override
                            public void onAdClicked(View view, int type) {
                                if (mAdInteractionListener != null)
                                    mAdInteractionListener.adClick(requestCode);
                            }

                            @Override
                            public void onAdShow(View view, int type) {
                                AdManage.showAdSuccess(mContext, adType, adIds.get(position, 0L),
                                        position, isIpReports.get(position, false));
                                if (mAdInteractionListener != null)
                                    mAdInteractionListener.adShow(requestCode);
                            }

                            @Override
                            public void onRenderFail(View view, String msg, int code) {
                                if (mAdInteractionListener != null)
                                    mAdInteractionListener.adFail(requestCode, msg);
                            }

                            @Override
                            public void onRenderSuccess(View view, float width, float height) {
                                YoYoAd interactionAd = new ToutiaoYoYoAd(n);
                                if (mAdInteractionListener != null)
                                    mAdInteractionListener.adReady(requestCode, interactionAd);
                            }
                        });
                        n.render();
                    }
                }
            }
        });
    }

    @Override
    public void onDestroy() {

    }
}
